﻿using System;
using System.Configuration;
using System.Net;

namespace Sustainalytics.Common.Configuration
{
    public class HostElement : ConfigurationElement
    {
        bool? _secured;
        
        [ConfigurationProperty("httpHostUrl",IsRequired = true)]
        public string HttpHostUrl
        {
            get { return (string)this["httpHostUrl"]; }
        }


        [ConfigurationProperty("httpsPort", IsRequired = true)]
        [IntegerValidator(MinValue = IPEndPoint.MinPort, MaxValue = IPEndPoint.MaxPort)]
        public int HttpsPort
        {
            get { return (int) this["httpsPort"];}
        }


        [ConfigurationProperty("secured", IsRequired = false, DefaultValue = false)]
        public bool Secured
        {
            get
            {
                if (_secured.HasValue)
                {
                    return _secured.Value;
                }
                
                return (bool)this["secured"]; 
            }
            set
            {
                _secured = value;
            }
        }

        

        public string GetAddress()
        {

            if (Secured)
            {

                var url = this.HttpHostUrl;
                var uriBuilder = new UriBuilder(url);
                uriBuilder.Scheme = Uri.UriSchemeHttps;
                uriBuilder.Port = this.HttpsPort;
                return uriBuilder.Uri.ToString();
            }
            else
            {
                return this.HttpHostUrl;
            }
        }
    }
    
}
